package com.sikaryofficial.workbench.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.sikaryofficial.common.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;

/**
 * 模板加载器
 */
@Component
@Slf4j
public class TemplateLoader {

    @Value("${template.dir}")
    private String templateDir;


    public InputStream load(String templateName) {
        File file = getFile(templateName);
        return FileUtil.getInputStream(file);
    }

    public void loadAndWrite(String templateName, OutputStream outputStream) {
        File file = getFile(templateName);
        try (InputStream inputStream = Files.newInputStream(file.toPath())) {
            IoUtil.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("copy file error", e);
            throw new ServiceException("copy file error");
        }
    }

    private File getFile(String templateName) {
        return new File(templateDir, templateName);
    }
}
